<?php

/**
 * IndexController - The default controller class
 * 
 * @author
 * @version 
 */

require_once 'Zend/Controller/Action.php';

class LoginController extends Zend_Controller_Action {

	public function indexAction() {
		$this->view->form = $this->getForm();
		$this->render ( 'formulario' );
	}
	
	public function acessarAction() {


		
		$this->_helper->viewRenderer->setNoRender ();
		
		$config = Zend_Registry::get ( 'config' );
		
		if (! $this->getRequest ()->isPost ()) {
			return $this->_forward ( '/index' );
		}
		
		$params = new Zend_Filter_Input(null, null, $this->getRequest()->getParams());
		
		$validatorLogin = new Zend_Validate();
		$validatorLogin->addValidator(new Valida_NaoVazio("login"));

		$validatorSenha = new Zend_Validate();
		$validatorSenha->addValidator(new Valida_NaoVazio("senha"));
				
		if (!$validatorLogin->isValid($params->login) || !$validatorSenha->isValid($params->senha)) {
			foreach($validatorLogin->getMessages() as $m)
				print $m."<br />";
			foreach($validatorSenha->getMessages() as $m)
				print $m."<br />";
			exit();
			
		}

			$params = new Zend_Filter_Input(null, null, $this->getRequest()->getParams());
			/* Adapter para o Zend Auth */
			
			$dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter ();
			
			$authAdapter = new Zend_Auth_Adapter_DbTable ( $dbAdapter, "usuarios", "login", "senha" );
			$authAdapter->setIdentity ( $params->login );
			$authAdapter->setCredential ( md5 ( $params->senha ) );
			$result = Zend_Auth::getInstance()->authenticate($authAdapter);
			
			if ($result->isValid()) {
				Zend_Auth::getInstance()->setStorage ( new Zend_Auth_Storage_Session ( $config->session->namespace ) );
				$usuario = $authAdapter->getResultRowObject ( null, "senha" );
				Zend_Auth::getInstance()->getStorage ()->write ( $usuario );
				
				$this->_redirect ( './' );
			
			} else {
				$mensagens = array ( );
				switch ( $result->getCode ()) {
					case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND :
						
					case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID :
						$mensagens [] = "Login e/ou senha inválidos";
					break;
					case Zend_Auth_Result::FAILURE_UNCATEGORIZED :
						$mensagens [] = "Erro desconhecido";
					break;
				}
				
				$this->view->mensagens = $mensagens;
											
				$this->render ( 'formulario' );
			}
		
	}
	
	
	
	private function getForm() {
		return new Forms_FormLogin ( array ('id' => 'formLogin' , 'action' => $this->view->baseUrl.'/'.$this->view->admindir.'/login/acessar', 'method' => 'post', 'id' => 'formLogin' ) );
	}
}
